package com.atguigu.demojuc.chap08;

/**
 * @author njg
 * @version 1.0
 * @date 2025/6/18 19:14
 */

import org.w3c.dom.ls.LSOutput;

import java.util.concurrent.*;

/**
 * 自定义线程池：
 *
 *    线程池线程数量如何设置？
 *      CPU密集型任务： CPU做很多计算，请求处理，非常忙。策略，不要创建过多的线程，不要让CPU频繁切换上下文。否则会影响系统性能。
 *          CPU + 1
 *
 *      I/O密集型任务：CPU笔记闲，I/O设备比较忙。策略：不能让CPU太闲，所以，需要创建更多的线程，让CPU忙起来。
 *          CPU * 2
 *
 */
public class CustomizeThreadPoolDemo {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                3, 5, 10, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy() //直接抛出异常
                //new ThreadPoolExecutor.CallerRunsPolicy() // 交给调用者线程处理
                //new ThreadPoolExecutor.DiscardOldestPolicy() // 丢弃排队最久的
                //new ThreadPoolExecutor.DiscardPolicy() // 丢弃刚来的任务
                (runnable, executor) -> {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t" + "线程池达到最大饱和，启动拒绝策略");
                    executor.submit(runnable);
                }
        );

        try {
            for (int i = 1; i <= 11; i++) {
                String num = String.valueOf(i);
                threadPoolExecutor.submit(()->{
                    System.out.println(Thread.currentThread().getName() + "\t" + "执行任务：i="+num);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }

    }
}
